<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body {
            margin: 0;
        }
        .ball {
            width: 100px;
            height: 100px;
            border-radius: 50%;
            background-color: red;
        }
    </style>
</head>
<body>

    <div class="ball"></div>

    <script src="../../../练习/jquery/jquery.js"></script>
    <script>
        // 使用jquery写全屏可拖动的小球(单个小球, 无需边缘检测)
        // 要求按下ctrl+z可以撤回到上一次小球的位置
        // 并在不能继续撤回时弹出警告框('已经撤回到底了')
        // (tiger)实现ctrl+y反撤回功能(反悔上一次撤回的操作)

        function getEvents() {
            let innerX = 0;
            let innerY = 0;
            let x = 0;
            let y = 0;
            const snapshots = [
                [x, y],
            ];

            return {
                onMouseMove(e) {
                    const { clientX, clientY } = e;
                    x = clientX - innerX;
                    y = clientY - innerY;
                    $('.ball').css({ transform: `translate(${ x }px, ${ y }px)` });
                },
                onMouseDown(e) {
                    innerX = e.offsetX;
                    innerY = e.offsetY;
                    $(document).on('mousemove', this.onMouseMove);
                },
                onMouseUp() {
                    snapshots.push([x, y]); // 记录x,y 用于撤回
                    $(document).off('mousemove', this.onMouseMove);
                },
                onKeyDown(e) {
                    if (e.ctrlKey && e.key === 'z') {
                        if (snapshots.length === 1) {
                            alert('撤到底了');
                            return;
                        }
                        // 撤回
                        snapshots.pop();
                        const [x, y] = snapshots.slice(-1)[0];
                        $('.ball').css({ transform: `translate(${ x }px, ${ y }px)` });
                    }
                },
            };
        }

        const events = getEvents();

        $('.ball').on('mousedown', events.onMouseDown.bind(events));
        $(document).on('mouseup', events.onMouseUp.bind(events));
        $(window).on('keydown', events.onKeyDown);
    </script>
</body>
</html>
